package com.fuda.trade.ui.holdings

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.fuda.trade.R
import com.fuda.trade.model.TradeHolding
import com.fuda.trade.model.TradeHoldingData

class HoldingsAdapter : ListAdapter<TradeHolding, HoldingsAdapter.HoldingViewHolder>(HoldingDiffCallback()) {

    companion object {
        val TAG: String = HoldingsAdapter::class.java.simpleName

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HoldingViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val itemView = when (viewType) {
            TradeHoldingData.Money::class.hashCode() -> inflater.inflate(R.layout.item_holding_money, parent, false)
            TradeHoldingData.Share::class.hashCode() -> inflater.inflate(R.layout.item_holding_share, parent, false)
            else -> throw IllegalArgumentException("Invalid view type")
        }
        return HoldingViewHolder(itemView)
    }
    
    override fun onBindViewHolder(holder: HoldingViewHolder, position: Int) {
        val holding = getItem(position)
        holder.bind(holding)
    }


    override fun getItemViewType(position: Int): Int {
        val tradeOrder: TradeHolding = getItem(position)
        return when (tradeOrder.data) {
            is TradeHoldingData.Money -> TradeHoldingData.Money::class.hashCode()
            is TradeHoldingData.Share -> TradeHoldingData.Share::class.hashCode()
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    class HoldingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private lateinit var description: TextView

        fun bind(tradeHolding: TradeHolding) {
            description = itemView.findViewById(R.id.description)
            description.text = TradeHolding.serialize(tradeHolding)
        }
    }



    class HoldingDiffCallback : DiffUtil.ItemCallback<TradeHolding>() {
        override fun areItemsTheSame(oldItem: TradeHolding, newItem: TradeHolding): Boolean {
            return oldItem::class == newItem::class && oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: TradeHolding, newItem: TradeHolding): Boolean {
            return oldItem == newItem
        }
    }
}